<template>
  <BaseMainSlot :show-btn-box="true">
    <!-- 加工批次完成 -->
    <template v-slot:btn-box>
      <ActionBar :page-no="24" :add-active="addActive" :del-active="delActive" :has-cancel="false" @add="add" @del="del" />
    </template>
    <template v-slot:search-box>
      <SearchBox @search="search">
        <div class="seach-box">
          <div class="select-box-content">
            <div class="select-box-content-name">批次名称：</div>
            <el-input v-model="querylist.processBatchName" placeholder="请输入批次名称" clearable />
          </div>
          <div class="select-box-content">
            <div class="select-box-content-name">批次号：</div>
            <el-input v-model="querylist.processBatchNo" placeholder="请输入批次号" clearable />
          </div>
          <div class="select-box-content">
            <div class="select-box-content-name">加工产品：</div>
            <el-select v-model="querylist.productMaterialNo" placeholder="请选择" clearable>
              <el-option v-for="item in productionOptions" :key="item.value" :label="item.name" :value="item.value" />
            </el-select>
          </div>
          <div class="select-box-content">
            <div class="select-box-content-name">加工产线：</div>
            <el-select v-model="querylist.productionLineNo" placeholder="请选择" clearable>
              <el-option v-for="item in productionLineOptions" :key="item.value" :label="item.name" :value="item.value" />
            </el-select>
          </div>
          <div class="select-box-content">
            <div class="select-box-content-name">加工时间：</div>
            <el-date-picker v-model="querylist.startTime" :picker-options="beginDate()" type="date" value-format="yyyy-MM-dd 00:00:00" placeholder="开始时间" />
            <el-date-picker v-model="querylist.endTime" :picker-options="processDate()" type="date" value-format="yyyy-MM-dd 23:59:59" placeholder="结束时间" />
          </div>
        </div>
      </SearchBox>
    </template>
    <template v-slot:table-box>
      <!-- :title="title" -->
      <tdtable :page="page" :prop-list="propList" :table-data="tableData" :show-index-column="showIndexColumn" :show-select-column="showSelectColumn" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange" @handleSelectionChange="handleSelectionChange">
        <template v-slot:estimatedProcessingQuantity="{ row }">
          <span v-if="row.estimatedProcessingQuantity">{{ row.estimatedProcessingQuantity }}{{ row.estimatedProcessingUnitName }}</span>
        </template>
        <template v-slot:rawMaterialQuantity="{ row }">
          <span v-if="row.rawMaterialQuantity">{{ row.rawMaterialQuantity }}{{ row.rawMaterialUnitName }}</span>
        </template>
        <template v-slot:jobTask="{ row }">
          <div v-if="row.processBatchNo" class="pointer" @click="showJobDialog(row)"><i class="el-icon-view"></i>查看</div>
        </template>
        <template v-slot:processTime="{ row }">
          <span v-if="row.processBatchNo">{{ row.startTime }}--{{ row.endTime }}</span>
        </template>
        <template v-slot:edit="{ row }">
          <div v-if="row.processBatchNo" class="operate">
            <div class="pointer" @click="edit(row)"><i class="el-icon-edit"></i>修改</div>
            <div class="pointer del" @click="alonedDel(row)"><i class="el-icon-delete"></i>删除</div>
          </div>
        </template>
      </tdtable>
    </template>
    <template v-slot:dialog>
      <AddEditDialog :show="show" :title-text="titleText" :production-options="productionOptions" :production-line-options="productionLineOptions" :raw-material-options="rawMaterialOptions" :raw-material-batch-options="rawMaterialBatchOptions" :process-batch-no="processBatchNo" :form-data-copy="formDataCopy" @rawMaterialChange="rawMaterialChange" @addEvent="addEvent" @closeDialog="closeDialog" />
      <!-- :productionProcessesDetails="productionProcessesDetails" -->
      <!-- @productionLineChange="productionLineChange" -->
      <AssociatedJobDialog :process-task-data="processTaskData" :show="isShowJobDialog" @closeDialog="closeJobDialog" />
    </template>
  </BaseMainSlot>
</template>

<script>
import ActionBar from '@/components/ActionBar/index1.vue';
import BaseMainSlot from '@/components/BaseMainSlot/newBaseMainSlot.vue';
import SearchBox from '@/components/SearchBox/index.vue';
import AddEditDialog from '../components/add-edit-dialog';
import AssociatedJobDialog from '../components/associated-job-dialog.vue';
// import SelectButton from "@/components/equipTypeSelectButton/selcetButton.vue";
import tdtable from '@/components/table/index.vue';
import ProcessBatchApi from '@/api/processing-management/process-batch-manage/process-batch-creation/index';
// 获取产品
import productionApi from '@/api/processing-management/basic-info-manage/processing-product-manage/index';
// 获取原料
import processingPrtApi from '@/api/processing-management/basic-info-manage/processing-material-manage/index';
// 获取产线
import productionLineApi from '@/api/processing-management/basic-info-manage/production-line-manage/index';
// 获取作业人
import jobTemplateApi from '@/api/processing-management/basic-info-manage/job-template-manage/index';
// 获取关联任务
// import processTaskApi from "@/api/process-management/processing-task";
// import UnitApi from "@/api/basic-info-manage/data-item-manage/index";
// import { mymixin } from "@/utils/mixin";
export default {
  name: 'ProcessBatchQuery',
  components: {
    ActionBar,
    AddEditDialog,
    BaseMainSlot,
    // SelectButton,
    tdtable,
    AssociatedJobDialog,
    SearchBox
  },
  // mixins: [mymixin],
  data() {
    return {
      processTaskData: [],
      formDataCopy: {},
      show: false,
      isShowJobDialog: false,
      isShowCompleteBatchDialog: false,
      addActive: true,
      delActive: false,
      titleText: '',
      productionOptions: [],
      productionLineOptions: [],
      rawMaterialOptions: [],
      rawMaterialBatchOptions: [],
      productionProcessesDetails: [],
      // dataItemIdOptions:[],
      // UnitOptions: [],
      // 编辑表单入参
      editObject: {},
      scopeRow: {},
      page: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      querylist: {
        processBatchName: '',
        processBatchNo: '',
        productMaterialNo: '',
        productionLineNo: '',
        startTime: ''
      },
      // title: "加工批次完成列表",
      propList: [
        { prop: 'processBatchName', label: '批次名称', minWidth: '100' },
        { prop: 'processBatchNo', label: '批次号', minWidth: '110' },
        { prop: 'productMaterialName', label: '加工产品', minWidth: '100' },
        {
          prop: 'estimatedProcessingQuantity',
          label: '估算加工量',
          minWidth: '100',
          slotName: 'estimatedProcessingQuantity'
        },
        { prop: 'rawMaterialName', label: '原料名称', minWidth: '100' },
        {
          prop: 'rawMaterialQuantity',
          label: '原料数量',
          minWidth: '100',
          slotName: 'rawMaterialQuantity'
        },
        { prop: 'productionLineName', label: '加工产线', minWidth: '100' },
        {
          prop: 'startTime',
          label: '加工时间(开始-结束)',
          minWidth: '260',
          slotName: 'processTime'
        },
        {
          prop: 'processingTaskList',
          label: '关联作业任务',
          minWidth: '120',
          slotName: 'jobTask'
        },
        { label: '操作', minWidth: '120', slotName: 'edit' }
      ],
      tableData: [],
      // 显示序号
      showIndexColumn: true,
      // 显示select
      showSelectColumn: true,
      processBatchNo: '',
      handle: '',
      handleSelectList: []
    };
  },
  computed: {},
  watch: {},
  mounted() {
    this.init();
    this.queryPageList();
  },
  methods: {
    // 限制前面日期不能低于后面日期
    beginDate() {
      const self = this;
      return {
        disabledDate(time) {
          if (self.querylist.endTime) {
            //  如果结束时间不为空，则小于结束时间
            return new Date(self.querylist.endTime).getTime() < time.getTime();
          } else {
            // return time.getTime() > Date.now(); // 开始时间不选时，结束时间最大值小于等于当天
          }
        }
      };
    },
    processDate() {
      const self = this;
      return {
        disabledDate(time) {
          if (self.querylist.startTime) {
            //  如果开始时间不为空，则结束时间大于开始时间
            self.time = new Date();
            return new Date(self.querylist.startTime).getTime() > time.getTime();
          } else {
            // return time.getTime() > Date.now(); // 开始时间不选时，结束时间最大值小于等于当天
          }
        }
      };
    },
    search() {
      this.queryPageList();
    },
    init() {
      this.getProductionOptions();
      this.getProductionLineOptions();
      this.getRawMaterialOptions();
      // this.getUnitOptions();
    },
    // 获取单位选择项
    // getUnitOptions() {
    //   UnitApi.queryUnit().then(res => {
    //     if (res.code === 1) {
    //       let list = [];
    //       res.data.forEach(item => {
    //         list.push({
    //           name: item.unitName,
    //           value: item.unitNo
    //         });
    //       });
    //       this.UnitOptions = list;
    //     }
    //   });
    // },
    // 获取加工批次号
    getInputStorageNo() {
      ProcessBatchApi.generateNo().then(res => {
        console.log(res);
        if (res.code === 1) {
          this.processBatchNo = res.data;
        }
      });
    },
    // 获取作业人数组
    getPersonOptions() {
      jobTemplateApi.queryPersonByCondition().then(res => {
        if (res.code === 1) {
          let list = [];
          res.data.forEach(item => {
            list.push({
              name: item.person.name,
              value: item.person.personNo
            });
          });
          this.PersonOptions = list;
        }
      });
    },
    // 获取产品选项
    getProductionOptions() {
      productionApi.queryByConditionList().then(res => {
        if (res.code === 1) {
          let list = [];
          res.data.forEach(item => {
            list.push({
              name: item.material.materialName,
              value: item.material.materialNo
            });
          });
          this.productionOptions = list;
        }
      });
    },
    // 获取产线选项
    getProductionLineOptions() {
      productionLineApi.queryByConditionList().then(res => {
        if (res.code === 1) {
          let list = [];
          // 提供表头搜索数据
          res.data.forEach(item => {
            list.push({
              name: item.productionLineName,
              value: item.productionLineNo
            });
          });
          this.productionLineOptions = list;
        }
      });
    },
    // 获取原料选项
    getRawMaterialOptions() {
      processingPrtApi.queryList().then(res => {
        if (res.code === 1) {
          let list = [];
          // 提供表头搜索数据
          res.data.forEach(item => {
            list.push({
              name: item.material.materialName,
              value: item.materialNo
            });
          });
          this.rawMaterialOptions = list;
        }
      });
    },
    // 获取批次信息
    getRawMaterialBatchOptions(val) {
      let parms = {
        materialNo: val
      };
      ProcessBatchApi.rawMaterialQueryByCondition(parms).then(res => {
        if (res.code === 1) {
          this.rawMaterialBatchOptions = res.data;
        }
      });
    },
    rawMaterialChange(val) {
      this.getRawMaterialBatchOptions(val);
    },
    // 获取产线绑定的工艺信息
    // getProductionProcessesDetail(val) {
    //   productionLineApi.queryDetailByNo(val).then(res => {
    //     if (res.code == 1) {
    //       this.productionProcessesDetails = res.data;
    //     }
    //   });
    // },
    // productionLineChange(val) {
    //   this.getProductionProcessesDetail(val);
    // },
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.queryPageList();
    },

    handleCurrentChange(val) {
      this.page.currentPage = val;
      this.queryPageList();
    },
    // 选中table行点击事件
    handleSelectionChange(val) {
      console.log(val);
      this.handleSelectList = [];
      this.handleSelectList = val.map(item => item.processBatchNo);
      if (this.handleSelectList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    queryPageList() {
      // 获取数据
      let param = {
        page: this.page.currentPage,
        size: this.page.pageSize,
        entity: {
          ...this.querylist,
          status: false,
          processBatchType: '自主生产'
        }
      };
      ProcessBatchApi.queryPageList(param).then(res => {
        if (res.code === 1) {
          let data = res.data;
          this.page.total = data.totalElements;
          this.tableData = data.content;
          this.addblankmet();
          this.resetActionBar();
        }
      });
    },
    // 添加物料
    addEvent(formData) {
      let params = { ...formData, processBatchType: '自主生产' };
      if (this.handle === 'add') {
        ProcessBatchApi.add(params).then(res => {
          console.log(res);
          if (res.code === 1) {
            this.$message.success(res.msg);
            this.queryPageList();
          }
        });
      }
      if (this.handle === 'edit') {
        ProcessBatchApi.edit(params).then(res => {
          console.log(res);
          if (res.code === 1) {
            this.$message.success(res.msg);
            this.queryPageList();
          }
        });
      }
    },
    // 单个删除
    alonedDel(e) {
      this.$confirm('此操作将永久删除该项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        customClass: 'myClass'
      })
        .then(() => {
          ProcessBatchApi.aloneDel(e.processBatchNo).then(res => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.queryPageList();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    // 批量删除
    del() {
      let params = {
        noList: this.handleSelectList
      };
      this.$confirm('此操作将永久删除该项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        customClass: 'myClass'
      })
        .then(() => {
          ProcessBatchApi.del(params).then(res => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.queryPageList();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    edit(row) {
      this.titleText = '加工批次修改';
      console.log(row);
      this.show = true;
      this.handle = 'edit';
      this.formDataCopy = { ...row };
    },
    closeDialog() {
      this.show = false;
    },
    showJobDialog(row) {
      this.isShowJobDialog = true;
      // processTaskApi
      //   .getListByConditon({ processBatchNo: row.processBatchNo })
      //   .then(res => {
      //     if (res.code === 1) {
      //       this.processTaskData = res.data || [];
      //     }
      //   });
      this.processTaskData = row.processingTaskList;
    },
    closeJobDialog() {
      this.isShowJobDialog = false;
    },
    closeCompleteBatchDialog() {
      this.isShowCompleteBatchDialog = false;
    },
    // 显示添加弹出框
    add() {
      this.titleText = '加工批次创建';
      this.formDataCopy = {};
      this.getInputStorageNo();
      this.show = true;
      this.handle = 'add';
    }
  }
};
</script>

<style scoped lang="scss">
@import '~@/styles/variables.scss';

::v-deep .el-collapse-item__header {
  height: 0px;
}
::v-deep .el-collapse-item__content {
  padding-bottom: 10px;
}
::v-deep .el-pagination {
  position: absolute;
  right: 0px;
  bottom: -18px;
}

::v-deep .el-form-item__label {
  min-width: 120px !important;
  text-align: end;
}
.total {
  position: absolute;
  top: 25px;
  left: 300px;
}

::v-deep .el-form-item.is-error {
  .el-input__inner {
    border-color: #f56c6c !important;
  }
}
.botton {
  background-color: #0091b7;
}
.select-box-content-name {
  width: 120px;
  text-align: right;
}
</style>
